package cc.tutorial.aop.aspect;

import cc.tutorial.aop.annotation.OperateLogAnnotation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created by rico on 2018/5/7.
 */
public class OperateLogInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(OperateLogInterceptor.class);

    /**
     * This implementation always returns {@code true}.
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("##OperateLogInterceptor.preHandle...");
        return super.preHandle(request, response, handler);
    }

    /**
     * This implementation is empty.
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("##OperateLogInterceptor.postHandle...");
    }

    /**
     * This implementation is empty.
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("##OperateLogInterceptor.afterCompletion...");
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        logger.info("methodName={}, paramter={}", method.getName(), method.getParameters());
        logger.info("##isAnnotationPresent={}", method.isAnnotationPresent(OperateLogAnnotation.class));
        OperateLogAnnotation annotation = method.getAnnotation(OperateLogAnnotation.class);
        logger.info("##value={}, operateName={}", annotation.value(), annotation.description());

    }

    /**
     * This implementation is empty.
     */
    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("##OperateLogInterceptor.afterConcurrentHandlingStarted...");
    }
}
